﻿using AspNetCore.Practice.Domain.Entities;
using AspNetCore.Practice.Domain.IRepositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SD.Infrastructure.AspNetCore;
using SD.Infrastructure.Constants;
using SD.Infrastructure.Global.Transaction;

namespace AspNetCore.Practice.AppService.Implements
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 单元事务
        /// </summary>
        private readonly IUnitOfWorkPractice _unitOfWork;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        /// <param name="unitOfWork"></param>
        public HomeController(IUnitOfWorkPractice unitOfWork)
        {
            this._unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            base.ViewBag.Start = "Hello World";
            base.ViewBag.CurrentSessionId = GlobalSetting.CurrentSessionId;

            return base.View();
        }

        /// <summary>
        /// 响应测试
        /// </summary>
        public void ResponseWriteTest()
        {
            OperationContext.HttpContext.Response.WriteAsync("OK").Wait();
        }

        /// <summary>
        /// 创建用户测试
        /// </summary>
        public void CreateUserTest()
        {
            User user = new User("user1", "用户1", "123456");

            this._unitOfWork.RegisterAdd(user);
            this._unitOfWork.UnitedCommit();
        }

        /// <summary>
        /// 创建信息系统测试
        /// </summary>
        /// <remarks>包含领域事件，同时创建系统管理员用户</remarks>
        public void CreateInfoSystemTest()
        {
            InfoSystem infoSystem = new InfoSystem("S001", "测试系统1", "Test001", ApplicationType.Web);

            this._unitOfWork.RegisterAdd(infoSystem);
            this._unitOfWork.UnitedCommit();
        }

        /// <summary>
        /// 修改用户测试
        /// </summary>
        public void UpdatePasswordTest()
        {
            User admin = this._unitOfWork.Resolve<User>(CommonConstants.AdminLoginId);
            admin.UpdatePassword("123456");

            this._unitOfWork.RegisterSave(admin);
            this._unitOfWork.UnitedCommit();
        }

        /// <summary>
        /// 初始化信息系统测试
        /// </summary>
        public void InitSystemTest()
        {
            InfoSystem authSystem = this._unitOfWork.Resolve<InfoSystem>("00");

            authSystem.Init("192.168.10.110", 8689, "http://192.168.10.110:8689/Home/Index");

            this._unitOfWork.RegisterSave(authSystem);
            this._unitOfWork.UnitedCommit();
        }

        /// <summary>
        /// AOP记录日志测试
        /// </summary>
        public void AopTest()
        {
            User user = new User("admin", "admin", null);

            this._unitOfWork.RegisterAdd(user);
            this._unitOfWork.UnitedCommit();
        }
    }
}
